package com.yudaxian.mq.listener;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Author: yudaxian
 * @Description: TODO
 * @DateTime: 2024/9/13 15:03
 **/
@Component
@Slf4j
public class MyRabbitMQListener {

    public static final String EXCHANGE_DIRECT = "exchange.direct.order";
    public static final String ROUTING_KEY = "order";
    public static final String QUEUE_NAME  = "queue.order";

    public static final String EXCHANGE_DELAY = "exchange.delay.video";
    public static final String ROUTING_KEY_DELAY = "routing.key.delay.video";
    public static final String QUEUE_DELAY = "queue.test.delay";
    public static final String QUEUE_PIORICITY = "queue.test.priority";
    //    @RabbitListener(queues = {QUEUE_NAME})
    public void processMessage(String dataString, Message message, Channel channel) throws IOException {

        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        try {
            System.out.println("消费端消息内容: " + dataString);

            // 操作成功，返回ACK
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            // 操作失败，返回NACK
            Boolean redelivered = message.getMessageProperties().getRedelivered();
            if (redelivered) {
                channel.basicNack(deliveryTag, false, false);
            }
            channel.basicNack(deliveryTag, false, true);
        }
    }

//    @RabbitListener(queues = {QUEUE_NAME})
    public void processMessageTestPrefetch(String dataString, Message message, Channel channel) throws IOException, InterruptedException {

        log.info("收到消息: " + dataString);

        TimeUnit.SECONDS.sleep(1);

        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

//    @RabbitListener(queues = {QUEUE_DELAY})
    public void processMessageDelay(String dataString, Message message, Channel channel) throws IOException {
        log.info("收到延迟消息: {}", dataString);
        log.info("延迟消息处理时间: {}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

    @RabbitListener(queues = {QUEUE_PIORICITY})
    public void processMessagePriority(String dataString, Message message, Channel channel) throws IOException {
        log.info("收到延迟消息: {}", dataString);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }

}
